package com.app.shortvideo.ui.common

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.webkit.*
import com.app.shortvideo.base.BaseActivity
import com.app.shortvideo.databinding.ActivityWebViewBinding
import com.app.shortvideo.utils.initWeb
import com.app.shortvideo.utils.loadWeb
import com.app.shortvideo.utils.jump.JumpUtils
import com.app.shortvideo.utils.jump.MaxityHosts
import com.app.library.base.LibViewModel
import com.app.library.ext.visible
import com.blankj.utilcode.util.LogUtils

class WebViewActivity : BaseActivity<ActivityWebViewBinding, LibViewModel>(){

    companion object {
        const val JS_HANDLER_OBJECT_NAME = "android"

        const val KEY_URL = "KEY_URL"
        const val KEY_TITLE = "KEY_TITLE"
        fun start(context: Context, url: String, title: String? = null) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra(KEY_URL, url)
            intent.putExtra(KEY_TITLE, title)
            context.startActivity(intent)
        }
    }

    private var mUrl: String? = null

    override fun initData(savedInstanceState: Bundle?) {
        val title = intent.getStringExtra(KEY_TITLE) ?: ""
        binding.titleView.setTitle(title)
        mUrl = intent.getStringExtra(KEY_URL) ?: ""
        binding.webView.loadWeb(mUrl)
    }

    override fun initView() {
        binding.webView.initWeb(this)
        binding.webView.webViewClient = object : WebViewClient() {

            override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
                LogUtils.d("shouldOverrideUrlLoading url:$url")
                if (TextUtils.isEmpty(url)) {
                    return false
                }
                val uri = Uri.parse(url)
                val scheme = uri.scheme
                if (TextUtils.equals(scheme, MaxityHosts.MAXITY_SCHEME)) {
                    JumpUtils.jumpToTarget(this@WebViewActivity, url)
                    return true
                }
                return if (url?.startsWith("http:") == true || url?.startsWith("https:") == true) {
                    view.loadUrl(url)
                    false
                } else {
                    try {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    true
                }
            }

            override fun onPageFinished(view: WebView, url: String?) {
                view.requestFocus()
                super.onPageFinished(view, url)
                binding.pbLoading.visible(false)
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                if (request?.isForMainFrame == true) {
                    binding.mEmptyCustomView.visible(true)
                    binding.webView.loadUrl("about:blank")
                }
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
                val code = errorResponse?.statusCode
                if (code == 500 || code == 502) {
                    binding.mEmptyCustomView.visible(true)
                    binding.webView.loadUrl("about:blank")
                }
            }
        }
    }

    override fun onBackPressed() {
        if (binding.webView.canGoBack()) {
            binding.webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        binding.webView.clearCache(true)
        super.onDestroy()
    }
}